<template>
	<view class="info-page">
		<!-- 个人信息列表 -->
		<view class="info-list">
			<!-- 头像 -->
			<view class="info-item">
				<!-- #ifdef MP-WEIXIN -->
				<button class="avatar-button" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
					<text class="label">更换头像</text>
					<view class="value-wrapper">
						<image class="avatar" :src="userInfo.avatar || require('@/static/public/logo.png')" mode="aspectFill"></image>
						<u-icon name="arrow-right" size="14" color="#AAAAAA"></u-icon>
					</view>
				</button>
				<!-- #endif -->
				
				<!-- #ifndef MP-WEIXIN -->
				<view class="info-item flex-between" style="padding: 0;" @tap="changeAvatar">
					<text class="label">更换头像</text>
					<view class="value-wrapper">
						<image class="avatar" :src="userInfo.avatar || require('@/static/public/logo.png')" mode="aspectFill"></image>
						<u-icon name="arrow-right" size="14" color="#AAAAAA"></u-icon>
					</view>
				</view>
				<!-- #endif -->
			</view>
			
			<!-- 昵称 -->
			<view class="info-item" @tap="showNicknamePopup">
				<text class="label">昵称</text>
				<view class="value-wrapper">
					<text class="value">{{ userInfo.nickname }}</text>
					<u-icon name="arrow-right" size="14" color="#AAAAAA"></u-icon>
				</view>
			</view>
			
			<!-- 手机号 -->
			<view class="info-item" @tap="showMobilePopup">
				<text class="label">手机号码</text>
				<view class="value-wrapper">
					<text class="value">{{ userInfo.mobile || ''  }}</text>
					<u-icon name="arrow-right" size="14" color="#AAAAAA"></u-icon>
				</view>
			</view>
			
			<!-- 邮箱 -->
			<view class="info-item" @tap="showEmailPopup">
				<text class="label">邮箱</text>
				<view class="value-wrapper">
					<text class="value">{{ userInfo.email || '' }}</text>
					<u-icon name="arrow-right" size="14" color="#AAAAAA"></u-icon>
				</view>
			</view>
			
			<!-- 性别 -->
			<view class="info-item" @tap="togglesex">
				<text class="label">性别</text>
				<view class="value-wrapper">
					<text class="value">{{ userInfo.sex === 1 ? '男' : '女' }}</text>
					<u-icon name="arrow-right" size="14" color="#AAAAAA"></u-icon>
				</view>
			</view>
			
			<!-- 发票设置 -->
			<view class="info-item" @tap="toInvoiceSetting">
				<text class="label">发票设置</text>
				<view class="value-wrapper">
					<u-icon name="arrow-right" size="14" color="#AAAAAA"></u-icon>
				</view>
			</view>
			
			<!-- 收藏电站 -->
			<view class="info-item" @tap="toFavoriteStations">
				<text class="label">收藏电站</text>
				<view class="value-wrapper">
					<u-icon name="arrow-right" size="14" color="#AAAAAA"></u-icon>
				</view>
			</view>
			
			<!-- 常用城市 -->
			<view class="info-item" @tap="showCityPicker = true">
				<text class="label">常用城市</text>
				<view class="value-wrapper">
					<text class="value">{{ userInfo.areaName || '请选择' }}</text>
					<u-icon name="arrow-right" size="14" color="#AAAAAA"></u-icon>
				</view>
			</view>
		</view>
		
		<!-- 退出登录 -->
		<view class="footer">
			<u-button color="#FF772C" shape="circle" text="退出登录" @click="logout"></u-button>
		</view>
		
		<!-- 修改昵称弹窗 -->
		<u-popup :show="showNickname" round="24" @close="showNickname = false" mode="center">
			<view class="nickname-popup">
				<view class="popup-title">修改昵称</view>
				<input 
					type="text"
					v-model="newNickname"
					class="nickname-input"
					placeholder="请输入昵称"
					placeholder-style="color: #AAAAAA"
				/>
				<view class="popup-btns">
					<text class="btn cancel" @tap="showNickname = false">取消</text>
					<text class="btn confirm" @tap="confirmNickname">确定</text>
				</view>
			</view>
		</u-popup>
		
		<u-popup :show="showMobile" round="24" @close="showMobile = false" mode="center">
		    <view class="nickname-popup">
		        <view class="popup-title">修改手机号码</view>
		        <input
		            type="tel"
		            v-model="newMobile"
		            class="nickname-input"
		            placeholder="请输入新手机号码"
		            placeholder-style="color: #AAAAAA"
		        />
		        <view class="code-container">
		            <input
		                type="text"
		                v-model="mobileCode"
		                class="nickname-input code-input"
		                placeholder="请输入验证码"
		                placeholder-style="color: #AAAAAA"
		            />
		            <text class="get-code" @click="getMobileCode">{{ codeMsg }}</text>
		        </view>
		        <view class="popup-btns">
		            <text class="btn cancel" @tap="showMobile = false">取消</text>
		            <text class="btn confirm" @tap="confirmMobile">确定</text>
		        </view>
		    </view>
		</u-popup>
		
		<u-popup :show="showEmail" round="24" @close="showEmail = false" mode="center">
		    <view class="nickname-popup">
		        <view class="popup-title">修改邮箱</view>
		        <input
		            type="text"
		            v-model="newEmail"
		            class="nickname-input"
		            placeholder="请输入新邮箱"
		            placeholder-style="color: #AAAAAA"
		        />
		        <view class="code-container">
		            <input
		                type="text"
		                v-model="emailCode"
		                class="nickname-input code-input"
		                placeholder="请输入验证码"
		                placeholder-style="color: #AAAAAA"
		            />
		            <text class="get-code" @click="getEmailCode">{{ emailCodeMsg }}</text>
		        </view>
		        <view class="popup-btns">
		            <text class="btn cancel" @tap="showEmail = false">取消</text>
		            <text class="btn confirm" @tap="confirmEmail">确定</text>
		        </view>
		    </view>
		</u-popup>
		
		<!-- 城市选择器 -->
		<city-picker 
			:show.sync="showCityPicker"
			@confirm="onCityConfirm"
		/>
	</view>
</template>

<script>
	import { mapState, mapActions } from 'vuex'
	import cityPicker from '@/components/city-picker/index.vue'
	export default {
		components: {
			cityPicker
		},
		data() {
			return {
				showNickname: false,
				newNickname: '',
				userInfo: {
					avatar: '',
					nickname: '',
					email: '',
					mobile: '',
					sex: 1,
					areaId: 0,
					areaName: ''
				},
				showCityPicker: false,
				cityInfo: null,
				showMobile: false, // 控制手机号修改弹窗显示
				newMobile: '', // 新手机号输入
				mobileCode: '', // 手机验证码输入
				codeMsg: '获取验证码', // 手机验证码按钮文本
			
				showEmail: false, // 控制邮箱修改弹窗显示
				newEmail: '', // 新邮箱输入
				emailCode: '', // 邮箱验证码输入
				emailCodeMsg: '获取验证码', // 邮箱验证码按钮文本
			
				mobileTimer: null,
				emailTimer: null,
			}
		},
		onLoad() {
			this.getMemberInfo()
		},
		methods: {
			...mapActions(['userLogoutAction']),
			// 获取用户信息
			getMemberInfo() {
				this.$http_api.userInfo({}).then((res)=>{
					this.userInfo = res;
				})
			},
			
			// 更换头像 - 微信小程序
			onChooseAvatar(e) {
				const avatarUrl = e.detail.avatarUrl
				this.uploadAvatar(avatarUrl);
			},
			
			// 更换头像 - App/H5
			changeAvatar() {
				// #ifndef MP-WEIXIN
				uni.chooseImage({
					count: 1,
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0]
						this.uploadAvatar(tempFilePath);
					}
				})
				// #endif
			},
			
			// 上传头像
			uploadAvatar(fileUrl) {
				this.$http_api.uploadFile(fileUrl).then(res => {
					this.userInfo.avatar = res;
					this.updateUserInfo();
				});
			},
			
			// 更新用户信息
			updateUserInfo() {
				this.$http_api.editUserInfo(this.userInfo)
			},
			
			// 显示昵称修改弹窗
			showNicknamePopup() {
				this.newNickname = this.userInfo.nickname
				this.showNickname = true
			},
			
			// 确认修改昵称
			confirmNickname() {
				if (!this.newNickname.trim()) {
					uni.$u.toast('昵称不能为空')
					return
				}
				this.userInfo.nickname = this.newNickname;
				this.showNickname = false
				this.updateUserInfo()
			},
			
			// 切换性别
			togglesex() {
				uni.showActionSheet({
					itemList: ['男', '女'],
					success: (res) => {
						this.userInfo.sex = res.tapIndex === 0 ? 1 : 2
						this.updateUserInfo()
					}
				})
			},
			
			// 跳转发票设置
			toInvoiceSetting() {
				uni.navigateTo({
					url: '/pages/user/users/info/invoice'
				})
			},
			
			// 跳转收藏电站
			toFavoriteStations() {
				uni.navigateTo({
					url: '/pages/user/users/info/collect'
				})
			},
			
			logout() {
				uni.showModal({
					title: '退出登录',
					content: '确认退出吗？',
					success: res => {
						if (!res.confirm) return;
						uni.removeStorageSync('token');
						this.userLogoutAction();
						this.$http_api.logout().then(res => {
							uni.redirectTo({ url: '/pages/public/login' })
						})
					}
				})
			},
			
			// 城市选择确认
			onCityConfirm(result) {
				this.cityInfo = result
				this.userInfo.areaId = this.cityInfo.city.id;
				this.userInfo.areaName = `${this.cityInfo.province.name}${this.cityInfo.city.name}`;
				this.updateUserInfo()
			},
			
			// 显示手机号修改弹窗
			    showMobilePopup() {
			        this.newMobile = '';
			        this.mobileCode = '';
			        this.codeMsg = '获取验证码';
			        this.showMobile = true;
			    },
			
			    // 显示邮箱修改弹窗
			    showEmailPopup() {
			        this.newEmail = '';
			        this.emailCode = '';
			        this.emailCodeMsg = '获取验证码';
			        this.showEmail = true;
			    },
			
			    // 获取手机验证码
			    async getMobileCode() {
			        if (this.codeMsg !== '获取验证码') return;
			        if (!this.newMobile || !uni.$u.test.mobile(this.newMobile)) {
			            uni.$u.toast('请输入正确的手机号码');
			            return;
			        }
			
			        try {
			            await this.$http_api.sendSmsCode({ mobile: this.newMobile, scene: 2 });
			            uni.$u.toast('验证码已发送');
			            let countdown = 60;
			            this.codeMsg = `${countdown} 秒后重试`;
			            this.mobileTimer = setInterval(() => {
			                if (countdown > 0) {
			                    countdown--;
			                    this.codeMsg = `${countdown} 秒后重试`;
			                } else {
			                    clearInterval(this.mobileTimer);
			                    this.mobileTimer = null;
			                    this.codeMsg = '获取验证码';
			                }
			            }, 1000);
			        } catch (e) {
			            console.error(e);
			        }
			    },
			
			    // 获取邮箱验证码
			    async getEmailCode() {
			        if (this.emailCodeMsg !== '获取验证码') return;
			        if (!this.newEmail || !uni.$u.test.email(this.newEmail)) {
			            uni.$u.toast('请输入正确的邮箱');
			            return;
			        }
			
			        try {
			            await this.$http_api.sendEmailCode({ email: this.newEmail, scene: 5 });
			            uni.$u.toast('验证码已发送');
			            let countdown = 60;
			            this.emailCodeMsg = `${countdown} 秒后重试`;
			            this.emailTimer = setInterval(() => {
			                if (countdown > 0) {
			                    countdown--;
			                    this.emailCodeMsg = `${countdown} 秒后重试`;
			                } else {
			                    clearInterval(this.emailTimer);
			                    this.emailTimer = null;
			                    this.emailCodeMsg = '获取验证码';
			                }
			            }, 1000);
			        } catch (e) {
			            console.error(e);
			        }
			    },
			
			    // 确认修改手机号
			    async confirmMobile() {
			        if (!this.newMobile || !this.mobileCode) {
			            uni.$u.toast('请填写完整信息');
			            return;
			        }
			        
			        try {
			            await this.$http_api.editUserMobile({
			                mobile: this.newMobile,
			                code: this.mobileCode,
			            });
			            uni.$u.toast('手机号修改成功');
			            this.userInfo.mobile = this.newMobile;
			            this.showMobile = false;
			        } catch (e) {
			            console.error(e);
			        }
			    },
			
			    // 确认修改邮箱
			    async confirmEmail() {
			        if (!this.newEmail || !this.emailCode) {
			            uni.$u.toast('请填写完整信息');
			            return;
			        }
			        
			        try {
			            await this.$http_api.editUserEmail({
			                email: this.newEmail,
			                code: this.emailCode,
			            });
			            uni.$u.toast('邮箱修改成功');
			            this.userInfo.email = this.newEmail;
			            this.showEmail = false;
			        } catch (e) {
			            console.error(e);
			        }
			    }
		}
	}
</script>

<style scoped lang="scss">
	.info-page {
		padding: 20rpx;
		
		.info-list {
			background: #FFFFFF;
			border-radius: 12rpx;
			padding: 0 30rpx;
			
			.info-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 30rpx 0;
				border-bottom: 1rpx solid #EEEEEE;
				width: 100%;
				
				&:last-child {
					border-bottom: none;
				}
				
				.label {
					font-size: 28rpx;
					color: #333333;
					font-family: "PINGFANG";
				}
				
				.value-wrapper {
					display: flex;
					align-items: center;
					
					.value {
						font-size: 28rpx;
						color: #666666;
						margin-right: 10rpx;
						font-family: "PINGFANG";
					}
					
					.avatar {
						width: 80rpx;
						height: 80rpx;
						border-radius: 50%;
						margin-right: 10rpx;
					}
				}
			}
			
			.avatar-button {
				width: 100%;
				background: none;
				padding: 0;
				display: flex;
				justify-content: space-between;
				align-items: center;
				
				&::after {
					border: none;
				}
				
				.label {
					font-size: 28rpx;
					color: #333333;
					font-family: "PINGFANG";
				}
				
				.value-wrapper {
					display: flex;
					align-items: center;
					
					.avatar {
						width: 80rpx;
						height: 80rpx;
						border-radius: 50%;
						margin-right: 10rpx;
					}
				}
			}
		}
		
		.nickname-popup {
			width: 600rpx;
			background: #FFFFFF;
			border-radius: 24rpx;
			padding: 30rpx;
			
			.popup-title {
				text-align: center;
				font-size: 32rpx;
				font-weight: bold;
				margin-bottom: 60rpx;
				font-family: "PINGFANG";
			}
			
			.nickname-input {
				height: 80rpx;
				background: #F5F5F5;
				border-radius: 8rpx;
				padding: 0 20rpx;
				font-size: 28rpx;
				font-family: "PINGFANG";
				margin-bottom: 60rpx;
			}
			
			.popup-btns {
				display: flex;
				justify-content: space-between;
				
				.btn {
					width: 260rpx;
					height: 80rpx;
					border-radius: 40rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 28rpx;
					font-family: "PINGFANG";
					
					&.cancel {
						background: #F5F5F5;
						color: #666666;
					}
					
					&.confirm {
						background: #1C6EFB;
						color: #FFFFFF;
					}
				}
			}
			
			// 弹窗容器样式
			    .code-container {
			        display: flex;
			        align-items: center;
			        margin-bottom: 60rpx;
			        .code-input {
			            flex: 1;
			            margin-right: 20rpx;
			        }
			        .get-code {
			            padding: 10rpx 20rpx;
			            border: 1rpx solid #1C6EFB;
			            border-radius: 8rpx;
			            color: #1C6EFB;
			            font-size: 24rpx;
						margin-top: -60rpx;
			            white-space: nowrap; // 防止文本换行
			        }
			    }
		}
	}

	.footer {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #FFFFFF;
		padding: 20rpx 40rpx;
		padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	}
</style>